import { toRaw } from "vue";
import { createPinia } from "pinia";

const setStorage = (key, value) => {
    localStorage.setItem(key, JSON.stringify(value))
}
const getStorage = (key) => {
    return JSON.parse(localStorage.getItem(key) ?? '""')
}
const __piniaKey__ = 'pinia'
const piniaPlugin = (options) => {
    return (context) => {
        const { store } = context;
        const data = getStorage(`${options?.key ?? __piniaKey__}_${store.$id}`)
        store.$subscribe(() => {
            setStorage(`${options?.key ?? __piniaKey__}_${store.$id}`, toRaw(store.$state))
        })
        return {
            ...data
        }
    }
}
const store = createPinia();

store.use(piniaPlugin({
    key: 'pinia'
}))

export default store